import os
import platform
import subprocess
import shutil
import sys

def clean_build():
    """清理构建文件"""
    dirs_to_clean = ['build', 'dist']
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
    
    # 清理 .spec 文件
    spec_file = 'docx2md.spec'
    if os.path.exists(spec_file):
        os.remove(spec_file)

def get_platform_options(use_icon=False):
    """根据不同平台返回打包选项"""
    system = platform.system().lower()
    
    # 获取项目根目录
    root_dir = os.path.dirname(os.path.abspath(__file__))
    
    common_options = [
        '--name=docx2md',
        '--onefile',
        '--noconsole',
        '--clean',
        f'--add-data={os.path.join(root_dir, "LICENSE")}{";" if system == "windows" else ":"}.',
        f'--add-data={os.path.join(root_dir, "README.md")}{";" if system == "windows" else ":"}.',
        # 添加src目录作为模块
        f'--add-data={os.path.join(root_dir, "src")}{";" if system == "windows" else ":"}src'
    ]
    
    # 只有在选择使用图标且图标文件存在时才添加图标选项
    if use_icon:
        icon_paths = {
            'windows': os.path.join(root_dir, 'resources', 'icon.ico'),
            'darwin': os.path.join(root_dir, 'resources', 'icon.icns'),
            'linux': os.path.join(root_dir, 'resources', 'icon.png')
        }
        
        platform_options = {
            'windows': [
                f'--icon={icon_paths["windows"]}',
                '--version-file=version_info.txt'
            ] if os.path.exists(icon_paths['windows']) else ['--version-file=version_info.txt'],
            'darwin': [
                f'--icon={icon_paths["darwin"]}',
                '--target-architecture=universal2'
            ] if os.path.exists(icon_paths['darwin']) else ['--target-architecture=universal2'],
            'linux': [
                f'--icon={icon_paths["linux"]}'
            ] if os.path.exists(icon_paths['linux']) else []
        }
    else:
        platform_options = {
            'windows': ['--version-file=version_info.txt'],
            'darwin': ['--target-architecture=universal2'],
            'linux': []
        }
    
    return common_options + platform_options.get(system, [])

def create_version_info():
    """创建 Windows 版本信息文件"""
    version_info = '''
VSVersionInfo(
  ffi=FixedFileInfo(
    filevers=(1, 0, 0, 0),
    prodvers=(1, 0, 0, 0),
    mask=0x3f,
    flags=0x0,
    OS=0x40004,
    fileType=0x1,
    subtype=0x0,
    date=(0, 0)
  ),
  kids=[
    StringFileInfo([
      StringTable(
        u'040904B0',
        [StringStruct(u'CompanyName', u'Snake Konginchrist'),
         StringStruct(u'FileDescription', u'Docx to Markdown Converter'),
         StringStruct(u'FileVersion', u'1.0.0'),
         StringStruct(u'InternalName', u'docx2md'),
         StringStruct(u'LegalCopyright', u'Copyright (c) 2024 Snake Konginchrist'),
         StringStruct(u'OriginalFilename', u'docx2md.exe'),
         StringStruct(u'ProductName', u'Docx to Markdown Converter'),
         StringStruct(u'ProductVersion', u'1.0.0')])
    ]),
    VarFileInfo([VarStruct(u'Translation', [0x0409, 1200])])
  ]
)
'''
    with open('version_info.txt', 'w', encoding='utf-8') as f:
        f.write(version_info)

def ask_yes_no(question):
    """询问用户是/否问题"""
    while True:
        response = input(f"{question} (y/n): ").lower().strip()
        if response in ['y', 'yes']:
            return True
        elif response in ['n', 'no']:
            return False
        print("请输入 y 或 n")

def check_requirements():
    """检查环境要求"""
    try:
        import docx
        import PyInstaller
    except ImportError as e:
        print(f"缺少必要的依赖包: {e}")
        print("请运行: pip install -r requirements.txt")
        return False
    return True

def build():
    """执行打包过程"""
    # 检查依赖
    if not check_requirements():
        return
    
    # 获取项目根目录
    root_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 检查源文件是否存在
    main_path = os.path.join(root_dir, 'src', 'main.py')
    if not os.path.exists(main_path):
        print(f"错误：找不到源文件 {main_path}")
        return
    
    # 清理旧的构建文件
    clean_build()
    
    # 询问用户是否需要使用图标
    use_icon = ask_yes_no("是否需要使用自定义图标？")
    
    if use_icon:
        # 确保资源目录存在
        resources_dir = os.path.join(root_dir, 'resources')
        if not os.path.exists(resources_dir):
            os.makedirs(resources_dir)
        
        print("\n如果需要使用图标，请确保在 resources 目录下放置了适当的图标文件：")
        print("Windows: icon.ico")
        print("MacOS: icon.icns")
        print("Linux: icon.png")
        input("\n按回车键继续...")
    
    # 如果是 Windows，创建版本信息文件
    if platform.system().lower() == 'windows':
        create_version_info()
    
    # 获取平台特定的选项
    options = get_platform_options(use_icon)
    
    # 构建命令
    python_exe = sys.executable
    cmd = [python_exe, '-m', 'PyInstaller'] + options + [main_path]
    
    # 执行打包命令
    try:
        print("\n开始打包...")
        print("执行命令:", ' '.join(cmd))
        subprocess.run(cmd, check=True)
        print(f"\n打包完成！可执行文件位于 dist 目录中")
    except subprocess.CalledProcessError as e:
        print(f"打包失败：{e}")
    except Exception as e:
        print(f"发生错误：{e}")
        print(f"错误类型: {type(e).__name__}")
        print(f"错误详情: {str(e)}")
    
    # 清理临时文件
    if os.path.exists('version_info.txt'):
        os.remove('version_info.txt')

if __name__ == "__main__":
    build() 